//
//  EWEDataPlayer.m
//  Auscultation
//
//  Created by 来 on 2020/12/6.
//

#import "EWEDataPlayer.h"
#import "EWEHeader.h"

@implementation EWEDataPlayer

- (id)init
{
    self = [super init];
    if (self) {
        isPlay = false;
        synlock = [[NSLock alloc] init];
        ///设置音频参数
        audioDescription.mSampleRate = LGF_SampleRate; //采样率
        audioDescription.mChannelsPerFrame = LGF_NumOfChannels; // 单声道
        audioDescription.mBitsPerChannel = LGF_SampleBits; //每个采样点16bit量化
        audioDescription.mFormatID = kAudioFormatLinearPCM;
        audioDescription.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
        audioDescription.mFramesPerPacket = 1;
        audioDescription.mBytesPerFrame = (audioDescription.mBitsPerChannel / 8) * audioDescription.mChannelsPerFrame;
        audioDescription.mBytesPerPacket = audioDescription.mBytesPerFrame * audioDescription.mFramesPerPacket;
        AudioQueueNewOutput(&audioDescription, AudioPlayerAQInputCallback, (__bridge void * _Nullable)(self), nil, 0, 0, &audioQueue);
        for (int i = 0; i < QUEUE_BUFFER_SIZE; i++) {
            audioQueueUsed[i] = false;
            ///创建buffer区，MIN_SIZE_PER_FRAME为每一侦所需要的最小的大小，该大小应该比每次往buffer里写的最大的一次还大
            AudioQueueAllocateBuffer(audioQueue, MIN_SIZE_PER_FRAME, &audioQueueBuffers[i]);
        }
        AudioQueueSetParameter(audioQueue, kAudioQueueParam_Volume, 3);
    }
    return self;
}

- (void)dealloc
{
    [self stop];
    if (audioQueue) {
        audioQueue = nil;
    }
    NSLog(@"EWEDataPlayer 已经释放");
}

- (void)stop
{
    if (audioQueue != nil) {
        AudioQueueStop(audioQueue, true);
        AudioQueueReset(audioQueue);
    }
    isPlay = false;
}

- (void)pause
{
    if (audioQueue) {
        if (isPlay) {
            NSLog(@"暂停");
            AudioQueuePause(audioQueue);
            isPlay = false;
        }
    } else {
        NSLog(@"audioQueue 为 nil");
    }
}

- (void)start
{
    if (audioQueue) {
        if (!isPlay || [self getNotUsedBuffers] == QUEUE_BUFFER_SIZE) {
            AudioQueueStart(audioQueue, NULL);
            isPlay = true;
        }
    } else {
        NSLog(@"audioQueue 为 nil");
    }
}

- (void)play:(NSData *)pcmData
{
    NSUInteger length = pcmData.length;
    Byte *bytes = (Byte *)malloc(length);
    [pcmData getBytes: bytes length: length];
    AudioQueueBufferRef audioQueueBuffer = [self getNotUsedBuffer];
    if (audioQueueBuffer) {
        audioQueueBuffer->mAudioDataByteSize = (unsigned int)length;
        memcpy(audioQueueBuffer->mAudioData, bytes, length);
        AudioQueueEnqueueBuffer(audioQueue, audioQueueBuffer, 0, NULL);
    }
}

static void AudioPlayerAQInputCallback(void* inUserData, AudioQueueRef outQ, AudioQueueBufferRef outQB)
{
    EWEDataPlayer* player = (__bridge EWEDataPlayer*)inUserData;
    [player playerCallback:outQB];
}

// 未使用的缓存
- (AudioQueueBufferRef)getNotUsedBuffer
{
    for (int i = 0; i < QUEUE_BUFFER_SIZE; i++) {
        if (!audioQueueUsed[i]) {
            audioQueueUsed[i] = true;
            return audioQueueBuffers[i];
        }
    }
    return NULL;
}

// 使用完的缓存
- (void)playerCallback:(AudioQueueBufferRef)outQB
{
    for (int i = 0; i < QUEUE_BUFFER_SIZE; i++) {
        if (audioQueueBuffers[i] == outQB) {
            audioQueueUsed[i] = false;
        }
    }
}

- (int)getNotUsedBuffers
{
    int ii = 0;
    for (int i = 0; i < QUEUE_BUFFER_SIZE; i++) {
        if (!audioQueueUsed[i]) {
            ii++;
        }
    }
    return ii;
}


@end
